package com.ml4ai.backend.stack.webcollector;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * Created by leecheng on 2018/10/28.
 */
public class TaskManager {

    private static TaskManager instance;
    private final List<Map<String, Object>> taskList;

    public TaskManager() {
        taskList = new ArrayList<>();
    }

    public static TaskManager getInstance() {
        if (instance == null) {
            synchronized (TaskManager.class) {
                instance = new TaskManager();
            }
        }
        return instance;
    }

    public List<Map<String, Object>> filter(Function<Map<String, Object>, Boolean> filter) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> task : taskList) {
            if (filter.apply(task)) {
                result.add(task);
            }
        }
        return result;
    }

    public TaskManager deleteBy(Function<Map<String, Object>, Boolean> function) {
        Iterator<Map<String, Object>> it = taskList.iterator();
        while (it.hasNext()) {
            Map<String, Object> task = it.next();
            if (function.apply(task)) {
                it.remove();
            }
        }
        return this;
    }

    public TaskManager add(Map<String, Object> task) {
        this.taskList.add(task);
        return this;
    }

}
